package com.itzhigui.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itzhigui.utils.ConstantUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 前台的控制器的拦截器
 *
 * @author java1412
 * @since 2023-11-14 17:38:05
 */
@Component
public class ApiLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是登录状态，放行,如果不使得状态不能访问
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute(ConstantUtil.LOGIN_USER_KEY);
        if (loginUser == null) {
            System.out.println("未登录");
            ObjectMapper om = new ObjectMapper();
            Map<String, Object> map = new HashMap<>();
            map.put("code", 400);
            map.put("msg", "用户没有登录，不能访问后续接口");
            String json = om.writeValueAsString(map);
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.write(json);
            out.flush();
            out.close();
            return false;
        } else {
            System.out.println("已登录");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
